<?php
/**
 * Created by PhpStorm.
 * User: 17628
 * Date: 2021-12-08
 * Time: 14:10
 */

namespace app\api\controller;


use app\admin\validate\Personal;
use app\common\controller\Api;
use app\admin\model\Personal as PersonalModel;
use think\Env;
use think\exception\ValidateException;
class Site extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 登录
     * account：账号
     * password：密码
     */
    public function login()
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(Personal::class)->scene('login')->check($postData);
            $resCode = $this->code($postData['code']);
//            halt($postData);终止
//            var_dump();打印不终止
            if (empty($resCode)) return errMsg(401,'登录失败');
            //  查询用户信息
            $model = new PersonalModel();
            $member = $model
                ->where('openid', $resCode->openid)
                ->field('id,nickname,avatar')
                ->find();
            //  判断用户是否注册
            if (empty($member)) {
                //  未注册，新增
                $add_member = [
                    'nickname' => base64_encode($postData['nickname']),
                    'openid' => $resCode->openid,
                    'avatar' => $postData['avatar'],
                ];
                $resAdd = PersonalModel::create($add_member);
                if (!$resAdd) return errMsg(402,'登陆失败');
                $user_id = $resAdd->id;
            } else {
                $user_id = $member['id'];
            }
            $token = signToken($user_id);
            $data = ['nickname' => $postData['nickname'], 'personal_id' => $user_id, 'token' => $token];
            return sucessMsg('登录成功！', $data);
        } catch (ValidateException $e) {
            return errMsg($e->getError());
        }
    }

    /**
     *
     * 根据code获取用户的openid等
     */
    public function code($code)
    {
        $appid = env::get('member.appid');
        $secret = env::get('member.secret');
        $res = [];
        if (empty($code)) return $res;
        $uri = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $resCode = json_decode(curlGet($uri));
        if (isset($resCode->openid)) $res = $resCode;
        return $res;
    }


    /**
     * @auth:
     * @date: 2021/10/11
     * @time: 11:14
     * @description:获取手机号
     */
//    public function mobile()
//    {
//        $postData = input('post.');
//        $code = $postData['code'];
//        $iv = $postData['iv'];
//        if (empty($code)) return errMsg('请传入code');
//        $resCode = $this->code($code);
//        if (empty($resCode)) return errMsg('data error！');
//        $sessionKey = $resCode->session_key;
//        $encryptedData = $postData['encrypted'];
//        $pc = new WXBizDataCrypt($this->appid, $sessionKey);
//        $errCode = $pc->decryptData($encryptedData, $iv, $data);
//        if ($errCode == 0) { //获取手机号成功
//            $res = json_decode($data)
//            $phone = $res->purePhoneNumber;  //手机号
//            return sucessMsg('成功', $phone);
//        } else {
//            return errMsg('失败');
//        }
//    }
}